<template>
    <div class="map-wrap">
      <div id="container"></div>
        <div class="thumb-icon" @click="viewTool = !viewTool" v-show="!viewTool && lineData.length > 0">
          <el-tooltip class="item" effect="dark" content="展开轨迹回放控制" placement="top-start">
            <!-- <i class="el-icon-d-arrow-right thumbIcon"></i> -->
            <el-icon :size="20" class="thumbIcon"><ArrowRightBold /></el-icon>
          </el-tooltip>
        </div>
        <div class="input-card" v-show="viewTool &&  lineData.length > 0">
          <div class="tool-content">
            <h4 class="toolTitle"><span>轨迹回放控制</span> <el-icon @click="viewTool = !viewTool"><Close /></el-icon></h4>
            <div class="input-item">
              <el-tooltip class="item" effect="dark" content="开始回放" placement="top-start">
                <el-button type="primary" :icon="VideoPlay" circle @click="startAnimation" size="large" class="btn"></el-button>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="暂停回放" placement="top-start">
                <el-button type="primary" :icon="VideoPause" circle @click="pauseAnimation" size="large" class="btn"></el-button>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="1.5倍速" placement="top-start">
                <el-button type="primary" circle @click="changeAnimation(1.5)" size="large" class="btn">1.5x</el-button>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="2倍速" placement="top-start">
                <el-button type="primary" circle @click="changeAnimation(2)" size="large" class="btn">2x</el-button>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="3倍速" placement="top-start">
                <el-button type="primary" circle @click="changeAnimation(3)" size="large" class="btn">3x</el-button>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="停止回放" placement="top-start">
                <el-button type="danger" :icon="Close" circle @click="stopAnimation" size="large" class="btn"></el-button>
              </el-tooltip>
            </div>
            <!-- <i class="el-icon-close toolClose" @click="viewTool = !viewTool"></i> -->
            <!-- <el-icon @click="viewTool = !viewTool"><Close /></el-icon> -->
          </div>
        </div>
    </div>
</template>

<script>
// import BMapGL from "BMapGL";
// import BMapGLLib from 'BMapGLLib';
import { ElLoading } from 'element-plus';
import {
  VideoPause,
  VideoPlay,
  Close,
} from '@element-plus/icons-vue'
import CarPng from '/images/car.png';
import start_markers from '/images/start_markers.png';
import end_markers from '/images/end_markers.png';
import dingwei_1 from '/images/dingwei_1.png';
export default {
  props: {
    lineData: {
      handler(val) {
        return val;
      },
      deep: true,
      immediate: true
    },
    stopData: {
      default: () => []
    }
  },
  data() {
    return {
      defaultSpeed: 1000,
      viewTool: false,
      map: null,
      loadingInstance: null,
      noteStart: 0, // 记录第一次点击开始回放,
      lushu: null,
      VideoPause,
      VideoPlay,
      Close,
    };
  },
  methods: {
    changeAnimation(speed) {
      this.lushu.stop();
      this.lushu._opts.speed = this.defaultSpeed * speed;
      this.lushu = this.lushu;
      this.lushu.start();
    },
    startAnimation() {
      this.lushu.start();
    },
    pauseAnimation() {
      this.lushu.pause();
    },
    stopAnimation() {
      this.lushu.stop();
      this.lushu._opts.speed = this.defaultSpeed;
      this.lushu = this.lushu;
    },
    initLine(){
      const that = this;

      // v3.0 路书
      let start= new BMapGL.Point(that.lineData[0][0],that.lineData[0][1]); // 设置起点
      let end= new BMapGL.Point(that.lineData[that.lineData.length - 1][0], that.lineData[that.lineData.length - 1][1]);  // 设置终点
      this.map.clearOverlays(); 

      // 驾车实例,并设置回调
      let driving = new BMapGL.DrivingRoute(that.map, {
        onSearchComplete: that.drawLine,
      });
      driving.search(start, end);
    },

    drawLine(results){
      const that = this;
      let bounds = []
      let planObj = results.getPlan(0);

      let addMarkerFun = function(point, imgType, index, title){
        let width;
        let height
        let myIcon;

        // imgType:1的场合，为起点和终点的图；2的场合为车的图形
        if(imgType == 1){
          width = 30;
          height = 34;
          myIcon = new BMapGL.Icon(index == 0 ? start_markers : end_markers, new BMapGL.Size(width, height), {
            offset: new BMapGL.Size(14, 30),
            // imageOffset: new BMapGL.Size(0, index * height)
          });
        }
        
        let marker = new BMapGL.Marker(point, {icon: myIcon});
        if(title != null && title != ""){
          marker.setTitle(title);
        }
        // 起点和终点放在最上面
        if(imgType == 1){
          marker.setTop(true);
        }
        that.map.addOverlay(marker);
      }
      
      let addPoints = function(points){
        for(let i = 0; i < points.length; i++){
          bounds.push(points[i]);
        }
      }	

      let arrPois = [];
      // 绘制驾车步行线路
      for (let i = 0; i < planObj.getNumRoutes(); i++){
        let route = planObj.getRoute(i);
        arrPois= arrPois.concat(route.getPath());
        if (route.getDistance(false) <= 0){continue;}
        addPoints(route.getPath());

        // 这里还可以细分，驾车还是步行等不同方式的路线，及设置对应的样式
        that.map.addOverlay(new BMapGL.Polyline(route.getPath(), {
          strokeColor: "#28F",
          strokeOpacity: 0.7,
          strokeWeight: 10,
          enableMassClear:true,
        }));
        
        let lushu = new BMapGLLib.LuShu(that.map, arrPois, {
          defaultContent: "",
          autoView: true, //是否开启自动视野调整，如果开启那么路书在运动过程中会根据视野自动调整
          icon  : new BMapGL.Icon(CarPng, new BMapGL.Size(52,26),{anchor : new BMapGL.Size(27, 13)}),
          speed: 1000,
          enableRotation:true, //是否设置marker随着道路的走向进行旋转
          landmarkPois: [], // 不管需不需要这个值一定要存在，空数据也要存在，不然开始回放动画的时候LuShu_min.js会一直报错，并且停止回放控制不可用
        });
        that.lushu = lushu;
      }	

      
      that.map.setViewport(bounds);

      // 终点
      addMarkerFun(results.getEnd().point, 1, 1);

      // 开始点
      addMarkerFun(results.getStart().point, 1, 0);
      that.loadingInstance.close();
    }

  },
  mounted() {
    const that = this;
    this.loadingInstance = ElLoading.service({
      target: '#container',
      lock: true,
      text: '正在加载中....',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, .45)'
    });
    let map = new BMapGL.Map('container');
    map.centerAndZoom(new BMapGL.Point(116.404, 39.915), 15);
    
    // 创建地址解析器实例
    let geoc = new BMapGL.Geocoder();
    that.map = map;
    
    if(this.stopData.length > 0) {
      let infoWindows = [];
      let coords = [];
      let clickInfoWindow;
      
      let interval = setInterval(open, 4500);
      let i = 0;
      function open() {
        if (!infoWindows[i].isOpen()) {
          map.openInfoWindow(infoWindows[i], coords[i]); //自动开启信息窗口
        }
        if (i == infoWindows.length - 1) {
          i = 0;
        } else {
          i++;
        }
      };
      

      // 信息窗口宽度 高度  
      let opts = { width: 300, height: 205 };
      this.stopData.forEach((item, i) => {
        let {hours, minutes, seconds} = this.timeFn(item.startTime, item.endTime);
        let lng = item.longitude / 1000000;
        let lat = item.latitude / 1000000;
        let point = new BMapGL.Point(lng, lat);
        coords[i] = point;

        let markerIcon = new BMapGL.Icon(
          dingwei_1,
          new BMapGL.Size(44, 44),          
        );
        let marker = new BMapGL.Marker(point, {
          icon: markerIcon
        });
        map.addOverlay(marker);
        map.centerAndZoom(point, 15);

        // 转换可用定位坐标点
        let _point = new BMapGL.Point(lng, lat);
        // 获取位置信息
        geoc.getLocation(_point, function(rs) {

          // 创建信息窗口对象 
          let infoWindow = new BMapGL.InfoWindow(`
            <div><span>核放单号: ${item.passPortNo}</span></div>
            <div><span>车牌号: ${item.vehicleNo}</span></div>
            <div><span>经度：${lng}</span></div>
            <div><span>纬度：${lat}</span></div>
            <div><span>停车时间始：${item.startTime}</span></div>
            <div><span>停车时间止：${item.endTime}</span></div>
            <div><span>停车时长：${hours}小时${minutes}分${seconds}秒</span></div>
            <div><span>位置: ${rs.address}</span></div>
          `, opts);

          infoWindows[i] = infoWindow;

          // 开启信息窗口
          map.openInfoWindow(infoWindow, point);
          marker.addEventListener("click", function(e){      
            map.openInfoWindow(infoWindow, point); 
            clearInterval(interval); // 停止自动开启信息窗口
            clickInfoWindow=infoWindow;

            interval = setInterval(function() {
              if (clickInfoWindow.isOpen()==false){
                clearInterval(interval);// 停止监测窗口
                interval = setInterval(open, 3000);// 自动开启信息窗口
              }
            }, 1000); //监测信息窗口是否关闭
          });
        })
      })
    }
    
    if(that.lineData.length > 0 ) {
      that.initLine();
    }
    map.enableScrollWheelZoom(true);
    let bottom_right_navigation = new BMapGL.NavigationControl({anchor: BMAP_ANCHOR_BOTTOM_RIGHT, type: BMAP_NAVIGATION_CONTROL_SMALL}); //右下角，仅包含平移和缩放按钮
    map.addControl(bottom_right_navigation);

    
  }  
}
</script>

<style lang="scss" scoped>
    #container{
      width: 100%;
      height: 80vh;
      background: rgba(0, 0, 0, .15);
    }
    .map-wrap {
      width: 100%;
      height: 80vh;
      background: rgba(0, 0, 0, .15);
      position: relative;
      .thumb-icon {
        position: absolute;
        top: 10px;
        left: 10px;
        width: 35px;
        height: 35px;
        border-radius: 50%;
        text-align: center;
        background: rgba(0, 0, 0, .45);
        border-bottom-right-radius: 35px;
        z-index: 99;
        cursor: pointer;
        transition: background .5s linear;
        &:hover {
          background: rgba(0, 0, 0, .7);
        }
        .thumbIcon {
          font-size: 22px;
          display: inline-block;
          margin-top: 5px;;
          color: #fff;
        }
      }
      .input-card {
        padding: 0 15px;
        position: absolute;
        top: 0;
        left: 0;
        z-index: 99;
        background: rgba(0, 0, 0, .55);
        border-bottom-right-radius: 35px;
        height: 130px;
        transition: display .5s linear;
        .btn{
          margin-right: .5rem;
          font-size: 20px;
        }
        ::v-deep .el-button+.el-button {
          margin-left: 0;
        }
        .btn:last-child{
          margin-right: 0;
          margin-top: 5px;
        }
      }

      .toolTitle {
        font-size: 20px;
        padding: 10px 0;
        color: #fff;
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
      .tool-content {
        position: relative;
        .toolClose {
          position: absolute;
          right: 0;
          top: 13px;
          color: #fff;
          font-size: 18px;
          cursor: pointer;
        }
      }
    }
    
</style>